package com.ad.aidai.fragments.register;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseFragment;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.utils.MultiStylesTextViewUtil;
import com.ad.aidai.common.widgets.edittext.ClearEditText;
import com.ad.aidai.common.widgets.edittext.PasswordEditText;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.fragments.service_item.ServiceItemFragment;
import com.orhanobut.logger.Logger;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 注册界面
 * <p>
 * Created by Yusxon on 16/12/7.
 */

public class RegisterFragment extends BaseFragment implements RegisterContract.View {

    @BindView(R.id.phone)
    ClearEditText phone;

    @BindView(R.id.password)
    PasswordEditText password;

    @BindView(R.id.verification_code_input)
    EditText verificationCodeInput;

    @BindView(R.id.register)
    Button button;

    @BindView(R.id.verification_code_button)
    Button verificationCodeButton;

    @BindView(R.id.reminder)
    TextView reminder;
    /**
     * 注册对话框
     */
    private LoadingDialog loadingDialog;


    private RegisterContract.Presenter mPresenter;


    @Override
    protected void initLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_register, container, false);
        mView.setClickable(true);
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        new RegisterPresenter(mContext, this).subscribe();
        reminder.setHighlightColor(ContextCompat.getColor(mContext, android.R.color.transparent));
        new MultiStylesTextViewUtil(mContext)
                .initTextView(reminder)
                .appendText("注册爱代账号表示已同意 《")
                .appendColorText("爱代服务条款", R.color.colorTheme, new MultiStylesTextViewUtil.OnTextClickListener() {
                    @Override
                    public void textClick(View v, String text) {
                        getFragmentManager()
                                .beginTransaction()
                                .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                                        .fragment_slide_left_exit)
                                .add(android.R.id.content, new ServiceItemFragment(), "service_item")
                                .addToBackStack("service_item")
                                .commit();
                    }
                })
                .appendText("》")
                .create();
    }

    @Override
    public void setPresenter(RegisterContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void showVerficationCodeCountDown(String time) {
        verificationCodeButton.setText(time);
    }

    @Override
    public void showLoading() {
        //显示加载对话框
        loadingDialog = new LoadingDialog(mContext);
        loadingDialog.setLoadingText("注册中...")
                .setSuccessText("注册成功")
                .setFailedText("注册失败")
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    @Override
    public void registerSuccess() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (loadingDialog.isShowing()) {

                }
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //注册成功,进入主页
                        RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.REGISTER_FINISHED, true));
                    }
                });
            }
        }).start();
    }

    @OnClick({R.id.register, R.id.verification_code_button, R.id.reminder, R.id.iv_back, R.id.rl_register_view})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register:
                mPresenter.register(phone.getText().toString(), password.getText().toString(), verificationCodeInput
                        .getText().toString());
                break;
            case R.id.verification_code_button:
                mPresenter.sendVerificationCode(phone.getText().toString());
                break;
            case R.id.iv_back:
                onActivityBackPressed();
                break;
            case R.id.rl_register_view:
                Logger.t(this.getClass().getSimpleName()).i("click");
                break;
        }
    }

    @Override
    public void setVCButtonClickable(boolean isClick) {
        if (!isClick) {
            verificationCodeButton.setClickable(false);
            verificationCodeButton.setTextColor(Color.WHITE);
            verificationCodeButton.setBackground(ContextCompat.getDrawable(mContext, R.drawable
                    .btn_get_code_after_shape));
        } else {
            verificationCodeButton.setClickable(true);
            verificationCodeButton.setText("发送验证码");
            verificationCodeButton.setTextColor(ContextCompat.getColor(mContext, R.color.register_verification_button));
            verificationCodeButton.setBackground(ContextCompat.getDrawable(mContext, R.drawable.btn_get_code_selector));
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.unSubscribe();
    }

    @Override
    public boolean onActivityBackPressed() {
        if (phone.isFocused()) {
            closeSoftInput(phone);
        } else if (password.isFocused()) {
            closeSoftInput(password);
        } else if (verificationCodeInput.isFocused()) {
            closeSoftInput(verificationCodeInput);
        }
        getFragmentManager().popBackStack();
        return false;
    }


    /**
     * 关闭软键盘
     *
     * @param view 对应的EditText
     */
    public void closeSoftInput(View view) {
        InputMethodManager inputManager = (InputMethodManager) mActivity.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}
